import { remove, getList, save } from '@/api/cust/cust'
import { getOptions } from '@/api/option'

import permission from '@/directive/permission/index.js'
import {isIdcard, isMobile, isEmail} from "../../../utils/validate";
import {Loading} from "element-ui";
export default {
  data() {
    return {
      formVisible: false,
      formTitle: '添加客户信息',
      docFormVisible: false,
      docFormTitle: '客户资料管理',
      isAdd: true,
      form: {
        mobile:'',
        cardType:'',
        cardNo:'',
        name:'',
        gender:'',
        registeAddr:'',
        contactsName:'',
        contactsTel:'',
        ownerFlag:'',
        email:'',
        wx:'',
        qq:'',
        homeTel:'',
        cardFrontFileId:'',
        cardBackFileId:'',
        contractFileId:'',
        state:'',
        inDate:'',
        outDate:'',
        id: '',
        createBy:'',
        createTime:'',
      },
      docForm:{
        id:'',
        mobile:'',
        name:'',
        cardFrontFileId:'',
        cardFrontFileUrl:'',
        cardBackFileId:'',
        cardBackFileUrl:'',
        contractFileId:'',
        contractFileUrl:'',
      },
      listQuery: {
        page: 1,
        limit: 20,
        id: undefined,
        mobile: undefined,
        name: undefined,
        cardNo: undefined
      },
      total: 0,
      list: null,
      listLoading: true,
      selRow: {},
      options:{
        gender:[],
        ownerFlag:[],
        cardType:[],
        state:[]
      },
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  computed: {

    //表单验证
    rules() {
      return {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            validator (rule, value, callback) {
              if (isMobile(value)) {
                callback()
              } else {
                callback(new Error('请输入正确手机号'))
              }
            },
            trigger: 'blur'
          }
        ],
        name:[
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur' }
        ],
        cardType: [
          { required: true, message: '请选择证件类型', trigger: 'blur' }
        ],
        cardNo: [
          { required: true, message: '请输入证件号码', trigger: 'blur' },
          {
            validator (rule, value, callback) {
              if (isIdcard(value)) {
                callback()
              } else {
                callback(new Error('请输入正确身份证号'))
              }
            },
            trigger: 'blur'
          }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        registeAddr:[
          { required: true, message: '请输入注册地', trigger: 'blur' },
          { min: 2, max: 64, message: '长度在 2 到 256 个字符', trigger: 'blur' }
        ],
        ownerFlag:[
          { required: true, message: '请选择客户类型', trigger: 'blur' }
        ],
        email:[
          {
            validator (rule, value, callback) {
              if (isEmail(value)) {
                callback()
              } else {
                callback(new Error('请输入正确身份证号'))
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.init()
    this.initOptions()
  },
  methods: {
    init() {
      this.fetchData()
    },
    initOptions(){
      getOptions('CardType_Gender_OwnerFlag_State').then(response => {
        this.options.cardType = response.data.maps.CardType;
        this.options.gender = response.data.maps.Gender;
        this.options.ownerFlag = response.data.maps.OwnerFlag;
        this.options.state = response.data.maps.State;
      })
    },
    fetchData() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.records
        this.listLoading = false
        this.total = response.data.total
      })
    },
    search() {
      this.fetchData()
    },
    reset() {
      this.listQuery.id = ''
      this.listQuery.mobile = ''
      this.listQuery.name = ''
      this.listQuery.cardNo = ''
      this.fetchData()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleClose() {

    },
    fetchNext() {
      this.listQuery.page = this.listQuery.page + 1
      this.fetchData()
    },
    fetchPrev() {
      this.listQuery.page = this.listQuery.page - 1
      this.fetchData()
    },
    fetchPage(page) {
      this.listQuery.page = page
      this.fetchData()
    },
    changeSize(limit) {
      this.listQuery.limit = limit
      this.fetchData()
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      this.selRow = currentRow
    },
    resetForm() {
      this.form = {
        mobile:'',
        cardType:'',
        cardNo:'',
        name:'',
        gender:'',
        registeAddr:'',
        contactsName:'',
        contactsTel:'',
        ownerFlag:'',
        email:'',
        wx:'',
        qq:'',
        homeTel:'',
        cardFrontFileId:'',
        cardBackFileId:'',
        contractFileId:'',
        state:'',
        inDate:'',
        outDate:'',
        id: ''
      }
    },
    add() {
      this.resetForm()
      this.formTitle = '添加客户信息',
      this.formVisible = true
      this.isAdd = true
    },
    docMng(id){
      this.docFormVisible = true;
      this.list.forEach((item, index) => {
          if(item.id === id){
            this.docForm = {
              id: id,
              name: item.name,
              mobile: item.mobile,
              cardFrontFileId: item.cardFrontFileId,
              cardFrontFileUrl: item.cardFrontFileUrl,
              cardBackFileId: item.cardBackFileId,
              cardBackFileUrl: item.cardBackFileUrl,
              contractFileId: item.contractFileId,
              contractFileUrl: item.contractFileUrl
            }
            return
          }
      })
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          save({
            mobile:this.form.mobile,
            cardType:this.form.cardType,
            cardNo:this.form.cardNo,
            name:this.form.name,
            gender:this.form.gender,
            registeAddr:this.form.registeAddr,
            contactsName:this.form.contactsName,
            contactsTel:this.form.contactsTel,
            ownerFlag:this.form.ownerFlag,
            email:this.form.email,
            wx:this.form.wx,
            qq:this.form.qq,
            homeTel:this.form.homeTel,
            cardFrontFileId:(this.form.cardFrontFileId === '' ? 0 : this.form.cardFrontFileId),
            cardBackFileId:(this.form.cardBackFileId === '' ? 0 : this.form.cardBackFileId),
            contractFileId:(this.form.contractFileId === '' ? 0 : this.form.contractFileId),
            state:this.form.state,
            inDate:this.form.inDate,
            outDate:this.form.outDate,
            id: this.form.id,
            createBy: this.form.createBy,
            createTime: this.form.createTime
          }).then(response => {
            this.$message({
              message: this.$t('common.optionSuccess'),
              type: 'success'
            })
            this.fetchData()
            this.formVisible = false
          })
        } else {
          return false
        }
      })
    },
    checkSel() {
      if (this.selRow && this.selRow.id) {
        return true
      }
      this.$message({
        message: this.$t('common.mustSelectOne'),
        type: 'warning'
      })
      return false
    },
    edit() {
      if (this.checkSel()) {
        this.isAdd = false
        this.form = this.selRow
        this.formTitle = '编辑客户信息'
        this.formVisible = true
      }
    },
    remove() {
      if (this.checkSel()) {
        var id = this.selRow.id
        this.$confirm(this.$t('common.deleteConfirm'), this.$t('common.tooltip'), {
          confirmButtonText: this.$t('button.submit'),
          cancelButtonText: this.$t('button.cancel'),
          type: 'warning'
        }).then(() => {
          remove(id).then(response => {
            this.$message({
              message: this.$t('common.optionSuccess'),
              type: 'success'
            })
            this.fetchData()
          }).catch( err=> {
            this.$notify.error({
              title: '错误',
              message: err
            })
          })
        }).catch(() => {
        })
      }
    },


    handleBeforeUpload() {
      if (this.uploadFileId !== '') {
        this.$message({
          message: this.$t('common.mustSelectOne'),
          type: 'warning'
        })
        return false
      }
      this.loadingInstance = Loading.service({
        lock: true,
        text: this.$t('common.uploading'),
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    handleUploadSuccess(response, raw) {
      this.loadingInstance.close()
      if (response.code === 20000) {
        console.log(response.data)
        this.uploadFileId = response.data.id
        this.form.fileName = response.data.originalFileName
      } else {
        this.$message({
          message: this.$t('common.uploadError'),
          type: 'error'
        })
      }
    }

  }
}
